<?php
namespace app\api\controller;

use think\Request;
use think\Db;
use think\controller\Rest;
use app\api\controller\Base;

/**
 *任务
 * 
 */
class Task extends Base
{

	/**
	 * 任务列表API
	 *
	 * @param [int] $[user_id] [用户ID]
	 * @param [string] $[keyword] [标题关键字]
	 * @param [int] $[star] [星标]
	 * @return [json] [description]
	 */
	public function taskList()
	{
		$Base = new Base();
		# 接收检索参数
		$data = input('');
		# 配置搜索参数

		$star = '';
		$status_str = 'status < 3';
		# 已完成
		if(isset($data['status']) && $data['status'] == 2)
		{
			$status_str = 'status = '.$data['status'];
		}else if(isset($data['status']) && $data['status'] == 1)
		{
			# 未完成
			$status_str = 'status = '.$data['status'];
		}
		$where = " and (part_id like '%".$data['user_id']."%' or creator_id=".$data['user_id']." or response_id=".$data['user_id'].")";
		# 星标
		if(!empty($data['star']))
		{
			$star = $data['star'];
			$where = " and star=".$star." and (part_id like '%".$data['user_id']."%' or creator_id=".$data['user_id']." or response_id=".$data['user_id'].")";
		}elseif (!empty($data['keyword'])) {
			# 关键字检索
			$where = " and title like '%".$data['keyword']."%' and (part_id like '%".$data['user_id']."%' or creator_id=".$data['user_id']." or response_id=".$data['user_id'].")";

		}elseif (!empty($data['star']) && !empty($data['keyword'])) {
			# 星标and关键字
			$where = " and star=".$star." and title like '%".$data['keyword']."%' and (part_id like '%".$data['user_id']."%' or creator_id=".$data['user_id']." or response_id=".$data['user_id'].")";
		}
		# 查询未完成任务数量
		$doing_count = db('task')->where('status = 1'.$where)->count();
		# 任务列表
		$where = $status_str.$where;
//		var_dump($where);exit;
		$taskList['list'] = db('task')->where($where)->order("add_time desc")->select();

		$map = [];
		foreach ($taskList['list'] as $key => $value) {
			# 处理时间
			$taskList['list'][$key]['start_time_c'] = strtotime($taskList['list'][$key]['start_time']);
			$taskList['list'][$key]['end_time_c'] = strtotime($taskList['list'][$key]['end_time']);
//			var_dump($taskList['list'][$key]['end_time']);
			$taskList['list'][$key]['task_start_time'] = $this->transTime($taskList['list'][$key]['start_time_c']);
			if($taskList['list'][$key]['end_time_c'] > strtotime("+1 year"))
			{
				$taskList['list'][$key]['task_end_time'] = date("Y-m-d H:i:s",$taskList['list'][$key]['end_time_c']);
			}else{
				$taskList['list'][$key]['task_end_time'] = date("m月d日 H:i",$taskList['list'][$key]['end_time_c']);
			}

			# 查询任务的子任务数量以及完成情况
			$taskList['list'][$key]['childTaskNum'] = db("task")->where('parent_id',$value['id'])->count();
			# 子任务完成数量
			$map['parent_id'] = $value['id'];
			$map['status'] = 2;
			$taskList['list'][$key]['wc_childTaskNum'] = db("task")->where($map)->count();
		}
		$taskList['doing_count'] = $doing_count;
		return $Base->json(200,'任务列表',$taskList);
	}

	/**
	 * 添加任务
	 * @param [array] $[data] [POST提交的数据]
	 * @return [json] [json数据]
	 */
	public function add()
	{
		# POST接收数据
		$data = input('post.');
		$user_id = session('User.id') ? session('User.id') : 1;
		$Base = new Base();
		if(empty($data['title']))
		{
			return $Base->json(0,'请输入任务名称');
		}
		if(!$data['demo_id'] && $data['demo_name'])
		{
			#创建新项目
			$demo = array(
				'demo_name' => $data['demo_name'],
				'user_id' => $user_id,
				'add_time' => date("Y-m-d H:i:s",time())
			);
			$data['demo_id'] = db('demo')->insertGetId($demo);
		}
		unset($data['demo_name']);
		# 创建新任务
		$data['creator_id'] = $user_id;
		$data['add_time'] = time();
		if(isset($data['part_id']))
		{
			$data['part_id'] = implode(',', $data['part_id']);
		}
		if(isset($data['url'])){
			$data['url'] = serialize($data['url']);
		}

		$res_id = db('task')->insertGetId($data);
		if($res_id)
		{
			$log = array(
				'task_id' => $res_id,
				'user_id' => $user_id,
				'text' => "创建新任务[".$data['title']."]",
				'create_time' => time()
			);
			$log_res = db('task_logs')->insert($log);
			return $Base->json(200,'任务创建成功');
		}else{
			return $Base->json(400,'任务创建失败');
		}
	}

	/**
	 *文件上传
	 *@param [object] $[name] [description]
	 * 
	 */
	public function uploadImage()
	{

	    $file = request()->file('files'); 
	    $Base = new Base();
	    if (empty($file)) { 
	      $this->error('请选择上传文件'); 
	    }
	    # 获取源文件名
	    $filename = $file -> getInfo()['name'];

	    //移动到框架应用根目录/public/uploads/ 目录下 
	    $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'); 
	    if ($info) { 
	      return $Base->json(200,'文件上传成功',array('url' => $_SERVER['HTTP_HOST']."/public/uploads/".$info->getSaveName(),'url_name' => $filename));
	    } else { 
	      //上传失败获取错误信息 
	      // $this->error(); 
	      return $Base->json(400,$file->getError()); 
	    } 
	}
	/**
	 * 任务详情
	 * 
	 * @param [int] $[id] [任务ID]
	 * @return [json] [任务信息]
	 */
	public function detail()
	{
		$Base = new Base();
		
		# 获取任务ID
		$id = input('post.id');
		if(!is_numeric($id))
		{
			return $Base->json(400,'任务标识错误');
		}
		# 查询任务
		$taskInfo = db("task")->where('id',$id)->find();
		if(!$taskInfo)
		{
			return $Base->json(400,"任务不存在");
		}
		#处理文件名
		$taskInfo['url'] = unserialize($taskInfo['url']);
		# 查询任务所属项目
		$demoInfo = db("demo")->where('id',$taskInfo['demo_id'])->find();
		if($demoInfo)
		{
			$taskInfo['demo_name'] = $demoInfo['demo_name'];
		}
		# 查询公司信息
		$companyInfo = db('company')->where('id',$taskInfo['ascription'])->find();
		if(!$companyInfo)
		{
			$taskInfo['company_name'] = "与好友协作";
		}
		# 查询负责人信息
		$responseInfo = db('users')->where('id',$taskInfo['response_id'])->field('id,name')->find();
		$taskInfo['response_name'] = $responseInfo['name'];
		# 查询合作者信息
		$partList = db('users')->where('id','in',$taskInfo['part_id'])->field('id,name')->select();
		$taskInfo['partList'] = $partList;
		# 循环查询任务的父级任务
		$parentList = $this->parentList($taskInfo['parent_id']);
		$taskInfo['parentList'] = $parentList;
		# 查询任务标签信息
		$labelList= db('label')->where('id',$taskInfo['label'])->find();
		$taskInfo['labelList'] = $labelList;
		# 查询当前任务下的子任务
		$child_tasks = db("task")->where('parent_id',$taskInfo['id'])->field('id,title')->select();
		$taskInfo['child_tasks'] = $child_tasks;
		$taskInfo['child_count'] = count($child_tasks);
		
		return $Base->json(200,'查询成功',$taskInfo);

	}
	/**
	 * 递归查询父级任务
	 *
	 * @param [int] $[parent] [任务父级ID]
	 * @return [array] [数组]
	 */
	public function parentList($parent_id)
	{
		static $arr = array();
		$task = db('task')->where('id',$parent_id)->field('id,title')->find();
		$arr[] = $task;
		if($task['parent_id'] != 0)
		{
			$this->partList($task['parent_id']);
		}
		return $arr;
	}
	/**
	 * 编辑任务
	 * @param [int] $[id] [任务ID]
	 * @return [json] [编辑成功或失败]
	 * 
	 */
	public function edit()
	{
		# POST接收数据
		$data = input('post.');
		$uid = session('User.id') ? session('User.id') : 1;
		$Base = new Base();

		if(!$data['id'])
		{
			return $Base->json(400,'任务ID不存在');
		}
		# 查询任务
		$taskInfo = db("task")->where('id',$data['id'])->field('id,title,creator_id,response_id')->find();
		if(!$taskInfo)
		{
			return $Base->json(400,'任务不存在');
		}
		if($uid != $taskInfo['creator_id'] && $uid != $taskInfo['response_id'])
		{
			return $Base->json(400,"无权修改");
		}

		if(isset($data['part_id']))
		{
			$data['part_id'] = implode(',', $data['part_id']);
		}
		if(isset($data['url'])){
			$data['url'] = serialize($data['url']);
		}

		// 启动事务
//		Db::startTrans();
//		try{
			# 修改主任务
//		$res = db('task')->update($data);
			# 判断是否修改子任务的状态
//			if(isset($data['child_type']) && is_numeric($data['child_type']))
//			{
//				$childList = db()->where("parent_id",$taskInfo['id'])->select();
//				foreach($childList as $k => $val)
//				{
//					$child_res = db('task')->where('id',$val['id'])->update(['status' => $data['status']]);
//				}
//			}
			// 提交事务
//			Db::commit();
//		} catch (\Exception $e) {
//			// 回滚事务
//			Db::rollback();
//			return $Base->json(400,'编辑失败');
//		}
		$res = db('task')->update($data);
		if($res)
		{
			$log = array(
				'task_id' => $data['id'],
				'user_id' => $uid,
				'text' => "修改了任务[".$taskInfo['title']."]",
				'create_time' => time()
			);
			$log_res = db('task_logs')->insert($log);

			return $Base->json(200,'编辑成功');
		}else{
			return $Base->json(400,'编辑失败');
		}

	}

	/**
	 * 修改任务状态或标识
	 * 
	 *@param [int] $[data] [标识数据]
	 * @return [json] [操作反馈]
	 */
	public function updateStatus()
	{
		$Base = new Base();
		$data = input('post.');
		if(!is_numeric($data['id']))
		{
			return $Base->json(400,"任务ID错误");
		}
		// 启动事务
		Db::startTrans();
		try{
			# 修改主任务
			$res = db('task')->update($data);
			# 判断是否修改子任务的状态
			if(isset($data['child_type']) && is_numeric($data['child_type']))
			{
				$childList = db()->where("parent_id",$data['id'])->select();
				foreach($childList as $k => $val)
				{
					$child_res = db('task')->where('id',$val['id'])->update(['status' => $data['status']]);
				}
			}
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			return $Base->json(400,'编辑失败');
		}
//		if($res)
//		{
			return $Base->json(200,"操作成功");
//		}else{
//			return $Base->json(400,'操作失败');
//		}

	}

	/**
	 *获取任务标签
	 *
	 */
	public function label()
	{
		$data = input('post.');
		$Base = new Base();
		# 获取任务所有标签
		$label = db('label')->select();

		return $Base->json(200,"任务标签",$label);
	}

	/*
	时间转换函数
	*/

	public function transTime($ustime) 
	{             

		$ytime = date("Y-m-d H:i",$ustime);

		$rtime = date("m月d日 H:i",$ustime);

		$htime = date("H:i",$ustime);  

		$time = time() - $ustime;

		$todaytime = strtotime("today"); 

		$time1 = time() - $todaytime;  

		# 获取明年时间戳
		$nextYear = strtotime("+1 year");
		if($time < 60){    
			$str = '刚刚';       

		}else if($time < 60 * 60){  

			$min = floor($time/60);                      

			$str = $min.'分钟前';              

		}else if($time < $time1){   

			$str = '今天'.$htime;    

		}else if($ustime > $nextYear){
			$str = $ytime;
		}else{

			$str = $rtime;   

		}                
		return $str;  

	} 
	
}
?>